import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/services.dart' show rootBundle;
class Test_File_io extends StatefulWidget {
  const Test_File_io({super.key});

  @override
  State<Test_File_io> createState() => _Test_File_io();
}

class _Test_File_io extends State<Test_File_io> {
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    //从文件读取点击次数
    _readCounter().then((int value) {
      setState(() {
        _counter = value;
      });
    });
  }

  _incrementCounter() async {
    setState(() {
      _counter++;
    });
    // 将点击次数以字符串类型写到文件中
    await (await _getLocalFile()).writeAsString('$_counter');
  }

  Future<File> _getLocalFile() async {
    // 获取应用目录
    String dir = (await getApplicationDocumentsDirectory()).path;
    return File('$dir/counter.txt');
  }

  Future<int> _readCounter() async {
    try {
      File file = await _getLocalFile();
      // 读取点击次数（以字符串）
      String contents = await file.readAsString();
      return int.parse(contents);
    } on FileSystemException {
      return 0;
    }
  }

  late final File _file;

  @override
  Widget build(BuildContext context) {
    // return Scaffold(
    //   appBar: AppBar(title: Text('文件操作')),
    //   body: Center(
    //     child: Text('点击了 $_counter 次'),
    //   ),
    //   floatingActionButton: FloatingActionButton(
    //     onPressed: _incrementCounter,
    //     tooltip: 'Increment',
    //     child: Icon(Icons.add),
    //   ),
    // );
    return Scaffold(
        appBar: AppBar(title: const Text('Test_File_io')),
        body: Column(children: [
          ElevatedButton(
              onPressed: () async {
                Directory baseUri = await getApplicationDocumentsDirectory();
                print('JtTag:baseUri:${baseUri.path}');
                _file = File('${baseUri.path}/dir/test.txt');
                // 创建目录
                _file.create(recursive: true);
              },
              child: Text('创建文件')),
          ElevatedButton(
              onPressed: () async {
                print('JtTag:exists:${await _file.exists()}');
              },
              child: Text('是否存在')),
          ElevatedButton(
              onPressed: () async {
                print('JtTag:readAsStringSync:${_file.readAsStringSync()}');
              },
              child: Text('读String')),
          ElevatedButton(
              onPressed: () async {
                print('JtTag:readAsBytesSync:${_file.readAsBytesSync()}');
              },
              child: Text('读Bytes')),
          ElevatedButton(
              onPressed: () async {
                print('JtTag:readAsLinesSync:${_file.readAsLinesSync()}');
              },
              child: Text('读Lines')),
          ElevatedButton(
              onPressed: () async {
                _file.writeAsString('hello world 你好');
              },
              child: Text('写')),
          ElevatedButton(
              onPressed: () async {
                // 打开一个 IOSink，后续可以多次写
                final sink = _file.openWrite(mode: FileMode.append);

                sink.writeln('第一条日志');
                sink.writeln('第二条日志');

                await sink.flush(); // 刷新缓存
                await sink.close(); // 关闭文件
              },
              child: Text('追加写')),
          ElevatedButton(
              onPressed: () async {
                // 1. 读取文件内容
                String content = await _file.readAsString();

                // 2. 替换标识符
                String newContent = content.replaceAll('world', 'worlds');

                // 3. 写回文件（覆盖写入）
                await _file.writeAsString(newContent);
              },
              child: Text('修改写')),
          ElevatedButton(
              onPressed: () async {
                // 定义要替换的标识符及值
                final replacements = {
                  '{{name}}': 'Jack',
                  '{{age}}': '25',
                  '{{city}}': 'Shanghai',
                  '{{job}}': 'Developer',
                  '{{hobby}}': 'Music',
                };

                await replaceInFile(_file, replacements);
                print('全部替换完成 ✅');
              },
              child: Text('修改多处写')),
          ElevatedButton(
              onPressed: () async {
                Directory baseUri = await getApplicationDocumentsDirectory();
                var logFile = File('${baseUri.path}/log.txt');
                // 追加
                // var sink = logFile.openWrite(mode: FileMode.append);
                var sink = logFile.openWrite();
                sink.write('FILE ACCESSED ${DateTime.now()}\n');
                await sink.flush();
                await sink.close();
              },
              child: Text('写入流')),
          ElevatedButton(
              onPressed: () async {
                Directory baseUri = await getApplicationDocumentsDirectory();
                var logFile = File('${baseUri.path}/log.txt');
                logFile.delete();
              },
              child: Text('删除文件')),
          ElevatedButton(
              onPressed: () async {
                Directory baseUri = await getApplicationDocumentsDirectory();
                String newPath = '${baseUri.path}/dir/test1.txt';
                _file.rename(newPath);
                // _file.create(recursive: true);
              },
              child: Text('修改文件名称')),
          ElevatedButton(
              onPressed: () async {
                Directory baseUri = await getApplicationDocumentsDirectory();
                String newPath = '${baseUri.path}/dir1/copy_test${Random().nextInt(1000)}.txt';
                File(newPath).createSync(recursive: true);
                _file.copySync(newPath);

              },
              child: Text('复制文件')),
          ElevatedButton(
              onPressed: () async {
                // 读取 assets 中的 JSON 文件
                String jsonString = await rootBundle.loadString('assets/petBreed.json');
                var data = jsonDecode(jsonString); // 解析 JSON
                print(data);

                // 遍历数据
                for (var item in data['birds']) {
                  print('${item['id']} - ${item['name']} - ${item['eName']}');
                }
              },
              child: Text('读取json文件')),
        ]));
  }

  Future<void> replaceInFile(
      File file, Map<String, String> replacements) async {
    // 1. 读取文件内容
    String content = await file.readAsString();

    // 2. 遍历替换
    replacements.forEach((from, to) {
      content = content.replaceAll(from, to);
    });

    // 3. 写回文件（覆盖写入）
    await file.writeAsString(content);
  }
}
